#================================================================
# Performes a full farm configuration backup is placed
# in E:\MyBackupLocation (NOTE: change this in var $backupLocation).
#
# Logs these events:
# - Application/SharePoint Backup: Information EventID=100: Starting scheduled SPFarmBackup
# - Application/SharePoint Backup: Information EventID=101: Finished scheduled SPFarmBackup without errors
# - Application/SharePoint Backup: Error EventID=102: Finished scheduled SPFarmBackup with Errors: <errormessage>
#
# Exitcodes:
# - ErrorLevel 1 =  Success
# - ErrorLevel 0 =  Failed
#================================================================

# Prepare Event Logging for SharePoint
$mySource = "SharePoint Backup"
$myLog = "Application"

# Backup Location
$backupLocation = "E:\MyBackupLocation" # NOTE: make sure permissions are sufficient

# Create a source if it does not exist, NOTE: using .NET since no good PowerShell alternative
if ([System.Diagnostics.EventLog]::SourceExists($mySource) -eq $false)
{
    New-EventLog -LogName $myLog -Source $mySource
}

# Start backup
Try
{
    # EventLog: start message
    Write-Eventlog -Logname $myLog -Source $mySource -EventID 100 -EntryType Information -Message "Starting scheduled SPFarmBackup" -Category 0

    # Load SharePoint snap-in
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
    
    # Here the actual backup is performed
    Backup-SPFarm -Directory "E:\FarmBackup" -BackupMethod Full -ConfigurationOnly # We only want configuration, let SQL Server backup content DBs

    # EventLog: finish message
    Write-Eventlog -Logname $myLog -Source $mySource -EventID 101 -EntryType Information -Message "Finished scheduled SPFarmBackup without errors" -Category 0
    
    # Stop this script and return exit code 1
    Exit 1 # 1 = success
}
Catch
{
    # EventLog: Error message
    Write-Eventlog -Logname $myLog -Source $mySource -EventID 102 -EntryType Error -Message "Finished scheduled SPFarmBackup with Errors: $_" -Category 0
    
    # Stop this script and return exit code 0 (Error)
    Exit 0 # 0 = failure
}